package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import finelProject.MyAppConstants;

/**
 * Servlet implementation class InsertUser
 */
public class InsertUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InsertUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Context context;
		try {
			context = new InitialContext();
			PrintWriter out = response.getWriter();
			BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();

			//get the data from the request
			String UserName 		= request.getParameter("Username");
			String Password 		= request.getParameter("Password");
			String NickName 		= request.getParameter("Nickname");
			String ShortDescription = request.getParameter("Description");
			String SetPhotoURL 		= request.getParameter("PhotoURL");
			
			//insert the User into the USERS table in the DB
			PreparedStatement stmt;
			try{
				stmt = conn.prepareStatement(MyAppConstants.INSERT_INTO_USERS);
				stmt.setString(1, UserName);
				stmt.setString(2, Password);
				stmt.setString(3, NickName);
				stmt.setString(4, ShortDescription);
				stmt.setString(5, SetPhotoURL);
				stmt.executeUpdate();
			
				//commit update
				conn.commit();
				//close statements
				stmt.close();
				// tell the client side about the new user
				out.print("Success");
			
			} catch (SQLException e) {
				getServletContext().log("Error while INSERT to FOLLOW", e);
				response.sendError(500);//internal server error
			}
			conn.close();
			//TODO: need to set the session to this specific user
		
		
		
		
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//TODO: need to send the client side the response
		response.setIntHeader("success", 1);
	}

}
